/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xml;
using System.Xml.Linq;
using System.Windows.Threading;
using System.Collections.Generic;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif
namespace Oceanside.Payments
{
    public static class PaymentEngine
    {
        public const int CONST_NO_DIALOG = 1;
        private static bool _hasPinDebit = false;
        public static bool HasPinDebit
        {
            get { return PaymentEngine._hasPinDebit; }
            set { PaymentEngine._hasPinDebit = value; }
        }
        private static bool _hasGift = false;
        public static bool HasGift
        {
            get { return PaymentEngine._hasGift; }
            set { PaymentEngine._hasGift = value; }
        }
        private static bool _hasCredit = false;
        public static bool HasCredit
        {
            get { return PaymentEngine._hasCredit; }
            set { PaymentEngine._hasCredit = value; }
        }

        private static decimal? _highTicketAmount;
        public static decimal? HighTicketAmount
        {
            get { return PaymentEngine._highTicketAmount; }
            set { PaymentEngine._highTicketAmount = value; }
        }

        public static bool InitializeAvailable()
        {
            try
            {
                List<PROCESSOR> pList = PROCESSOR.GetAll();
                int giftCount = 0;
                int creditCount = 0;
                int pinDebitCount = 0;
                bool identityInitialized = false;

                if (pList.Count > 0 && pList.Count <= 3)
                {
                    for (int index = 0; index < pList.Count; index++)
                    {
                        PROCESSOR p = pList[index] as PROCESSOR;

                        if (p.CardType.Equals("MERCCREDIT"))
                        {
                            HighTicketAmount = p.QuickServiceHighTicket;
                            creditCount++;
                            if (!identityInitialized)
                            {
                                PaymentEngine.InitIdentity(p.MerchantId, p.AllowPartial);
                                identityInitialized = true;
                            }
                            string response = PaymentEngine.InitCredit(p.EP1, p.EP2);
                            TRANSACTION_RESPONSE message = new TRANSACTION_RESPONSE();
                            if (response == null || !message.Parse(response) || !message.CmdStatusOk)
                            {
                                return false;
                            }
                            _hasCredit = true;
                        }
                        else if (p.CardType.Equals("MERCGIFT"))
                        {
                            giftCount++;
                            if (!identityInitialized)
                            {
                                PaymentEngine.InitIdentity(p.MerchantId, p.AllowPartial);
                                identityInitialized = true;
                            }
                            string response = PaymentEngine.InitGift(p.EP1, p.EP2);
                            TRANSACTION_RESPONSE message = new TRANSACTION_RESPONSE();
                            if (response == null || !message.Parse(response) || !message.CmdStatusOk)
                            {
                                return false;
                            }
                            _hasGift = true;
                        }
                        else if (p.CardType.Equals("MERCVER1000PIN"))
                        {
                            pinDebitCount++;
                            if (!identityInitialized)
                            {
                                PaymentEngine.InitIdentity(p.MerchantId, p.AllowPartial);
                                identityInitialized = true;
                            }
                            string response = PaymentEngine.InitDebit(p.PinDebitCom, p.ExtDevicePrompt);
                            TRANSACTION_RESPONSE message = new TRANSACTION_RESPONSE();
                            if (response == null || !message.Parse(response) || !message.CmdStatusOk)
                            {
                                return false;
                            }
                            _hasPinDebit = true;
                        }
                        else if (p.CardType.Equals("AUTHCREDIT"))
                        {
                            ///TODO
                        }
                        else if (p.CardType.Equals("NONE"))
                        {

                        }
                    }

                    if (pinDebitCount > 1 || creditCount > 1 || giftCount > 1)
                    {
                        return false;
                    }
                }
            }
            catch (Exception e)
            {
                Logging.LogException(e);
                return false;
            }
            return true;
        }

        private enum PROCTYPE_ENUM
        {
            GIFT,
            CREDIT
        }


        static DSICLIENTXLib.DSICLientX _xDSCredit;
        public static DSICLIENTXLib.DSICLientX CreditComChan
        {
            get { return PaymentEngine._xDSCredit; }
            set { PaymentEngine._xDSCredit = value; }
        }

        static DSICLIENTXLib.DSICLientX _xDSGift;
        public static DSICLIENTXLib.DSICLientX GiftComChan
        {
            get { return PaymentEngine._xDSGift; }
            set { PaymentEngine._xDSGift = value; }
        }

        static VER1000XLib.Ver1000X _xDsDebit;
        public static VER1000XLib.Ver1000X DebitComChan
        {
            get { return PaymentEngine._xDsDebit; }
            set { PaymentEngine._xDsDebit = value; }
        }

        static string _merhcantId;
        public static string MerchantId
        {
            get { return PaymentEngine._merhcantId; }
            set { PaymentEngine._merhcantId = value; }
        }


        static string _allowDuplicateOveride = null;
        public static string AllowDuplicateOveride
        {
            get { return PaymentEngine._allowDuplicateOveride; }
            set { PaymentEngine._allowDuplicateOveride = value; }
        }

        static string _allowPartialAuth = null;
        public static string AllowPartialAuth
        {
            get { return PaymentEngine._allowPartialAuth; }
            set { PaymentEngine._allowPartialAuth = value; }
        }


        public static void InitIdentity(string merchantId, bool allowPartial)
        {
            AllowDuplicateOveride = null;

            if (allowPartial)
            {
                AllowPartialAuth = "Allow";
            }
            else
            {
                AllowPartialAuth = null;
            }
            MerchantId = merchantId;
        }

        public static string InitCredit(string ep1, string ep2)
        {
            string response = null;
            try
            {
                CreditComChan = new DSICLIENTXLib.DSICLientX();
                response = CreditComChan.ServerIPConfig(ep1 + ";" + ep2, PaymentEngine.CONST_NO_DIALOG);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return response;
        }
        public static string InitGift(string ep1, string ep2)
        {
            string response = null;

            try
            {
                GiftComChan = new DSICLIENTXLib.DSICLientX();
                response = GiftComChan.ServerIPConfig(ep1 + ";" + ep2, PaymentEngine.CONST_NO_DIALOG);
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return response;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="comportStrInt">Use 1,2,3 etc. Not COM1, COM2, etc.</param>
        /// <returns></returns>
        public static string InitDebit(string comportStrInt, string devPrompt)
        {
            string response = null;
            try
            {
                DebitComChan = new VER1000XLib.Ver1000X();
                response = Debit.Init(comportStrInt, devPrompt);

            }
            catch (Exception e)
            {
                Logging.LogException(e);
            }
            return response;
        }

        public static string NullCheckGetText(XmlNodeList nodeList)
        {
            string innerText = null;
            if (nodeList != null && nodeList.Count > 0)
            {
                innerText = nodeList[0].InnerText;
            }
            return innerText;
        }
    }
}
